import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import type { routerList } from '../type/user'
import userStore from '../store/user'

const store = userStore()
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/',
      name: 'layout',
      component: () => import('../layout/LayoutView.vue')
    },
    {
      // 将匹配所有内容并将其放在 `$route.params.pathMatch` 下
      path: '/:pathMatch(.*)*',
      name: '404',
      component: () => import('../views/ErrorView.vue')
    }
  ]
})

router.beforeEach((to, from, next) => {//第一个参数要去的路径，第二个参数，从那个路径过来的，第三个可选参数》下一步
  let nextTo = '';
  if (to.path === '/login') next()//路径为登录页面直接放行
  else {//不为登录页面，再进行判断
    nextTo = to.path;
    sessionStorage.setItem('nextTo', nextTo)//将要取得地址存下来，登录后跳转过去
    const routerArr = router.getRoutes()//获取当前已有的路由权限个数

    
    if (routerArr.length > 4 ) {//判断当前路由已经动态添加路由了，个数大于初始个数3个
      if (to.path === '/') {
        next({ path: '/data/overview', replace: true })
      }
      next()
    } else {//没有添加路由
      const routerList = store.routes //获取本地缓存的路由
      if (!routerList) next({ path: '/login', replace: true })//本地缓存也没有,去登陆
      if (routerList && routerList.length !== 0) {//已经获取过，本地有权限，但是没有添加到路由表
        routerList.forEach((item: routerList) => {//遍历循环，将获取到的新路由添加到路由列表里
          if (item.component) {//父级的没有展示组件的排除
            router.addRoute('layout', {
              path: item.path,
              component: () => import(`../views/${item.component}.vue`)
            })
          }
        });
        next({ path: to.path, replace: true })//跳转到之前要去的地址
      } else next({ path: '/login', replace: true })//没有获取权限

    }
  }
})


export default router
